package com.woyou.fragment.order;

import java.util.ArrayList;
import java.util.List;

import com.jing.biandang.R;
import com.woyou.activity.HomeActivity;
import com.woyou.adapter.CancelOrderAdapter;
import com.woyou.bean.BoxFee;
import com.woyou.bean.DeliverFee;
import com.woyou.bean.FmInfo;
import com.woyou.bean.Remark;
import com.woyou.bean.rpc.HandleCancelReq;
import com.woyou.bean.rpc.HandleCancelRes;
import com.woyou.bean.rpc.QueryOrderDetailsReq;
import com.woyou.bean.rpc.QueryOrderDetailsRes;
import com.woyou.bean.rpc.Result;
import com.woyou.component.SuperUI;
import com.woyou.fragment.SuperFragment;
import com.woyou.model.OrderManageModel;
import com.woyou.model.rpc.OrderModel;
import com.woyou.utils.FormatTools;
import com.woyou.utils.LightManager;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.SoundManager;
import com.woyou.utils.ThreadPoolManager;
import com.woyou.utils.TypeJudgeTools;

import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CancelOrderFragment extends SuperFragment implements
		OnClickListener {
	private HomeActivity homeActivity;
	private View cancelOrder;
	private TextView layout_cancelorder_num;
	private TextView layout_cancelorder_time;
	private TextView layout_cancelorder_address;
	private TextView layout_cancelorder_name;
	private TextView layout_cancelorder_sex;
	private TextView layout_cancelorder_sum;
	private RelativeLayout layout_cancelorder_disagree;
	private RelativeLayout layout_cancelorder_agree;

	private ListView layout_cancelorder_lv;
	private CancelOrderAdapter cancelOrderAdapter;
	private List<Object> goodsList=new ArrayList<Object>();
	//
	private OrderModel orderModel;
	private OrderManageModel omModel = OrderManageModel.getInstance();

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (hidden) {
			// 判断是否5分钟可以切换
			homeActivity.isCanSwitchView = true;
		}else{
			initData();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		cancelOrder = inflater.inflate(R.layout.layout_cancelorder, container,false);
		homeActivity=(HomeActivity)getActivity();
		orderModel = OrderModel.getInstance(homeActivity);
		return cancelOrder;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
		initData();
	}

	/**
	 * 初始化页面
	 */
	public void initView() {

		layout_cancelorder_num = (TextView) cancelOrder.findViewById(R.id.layout_cancelorder_num);
		layout_cancelorder_time = (TextView) cancelOrder.findViewById(R.id.layout_cancelorder_time);
		layout_cancelorder_address = (TextView) cancelOrder.findViewById(R.id.layout_cancelorder_address);
		layout_cancelorder_name = (TextView) cancelOrder.findViewById(R.id.layout_cancelorder_name);
		layout_cancelorder_sex = (TextView) cancelOrder.findViewById(R.id.layout_cancelorder_sex);
		layout_cancelorder_sum = (TextView) cancelOrder.findViewById(R.id.layout_cancelorder_sum);
		layout_cancelorder_disagree = (RelativeLayout) cancelOrder.findViewById(R.id.layout_cancelorder_disagree);
		layout_cancelorder_agree = (RelativeLayout) cancelOrder.findViewById(R.id.layout_cancelorder_agree);
		layout_cancelorder_lv = (ListView) cancelOrder.findViewById(R.id.layout_cancelorder_lv);

		layout_cancelorder_disagree.setOnClickListener(this);
		layout_cancelorder_agree.setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	public void initData() {
		// 判断是否5分钟可以切换
		homeActivity.isCanSwitchView = false;
		// 显示蒙版，屏蔽actionbar上的点击事件
		homeActivity.actionbarView.actionBarController.showMask();
		ThreadPoolManager.getInstance().executeTask(new Runnable() {

			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					if (homeActivity.homeController.cancelOrderList != null&&homeActivity.homeController.cancelOrderList.size()>0) {
						// 获取新订单详情
						QueryOrderDetailsReq queryOrderDetailsReq=new QueryOrderDetailsReq();
						queryOrderDetailsReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
						queryOrderDetailsReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
						queryOrderDetailsReq.setoId(homeActivity.homeController.cancelOrderList.get(0));
						Log.i("Order", ""+homeActivity.homeController.cancelOrderList.get(0));
						Result<QueryOrderDetailsRes> result= orderModel.v2_3queryOrderDetails(queryOrderDetailsReq);
						if(result!=null&&result.getCode()==1){
							LightManager.turnOnRedLight(true);
							SoundManager.getInstance(mContext).playSound(SoundManager.CANCELORDER);
							showOrderDetails(result.getData());
						}else if(result!=null&&result.getCode()==-3){
							homeActivity.homeController.exitLogin();
						}else{
							homeActivity.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									SuperUI.openToast(homeActivity, "该订单号无效");
								}
							});
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}
	/**
	 * 显示订单详情
	 */
	public void showOrderDetails(final QueryOrderDetailsRes queryOrderDetailsRes){
		homeActivity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				layout_cancelorder_num.setText(queryOrderDetailsRes.getShortNo());
				String time=FormatTools.convertTime(queryOrderDetailsRes.getReserveTime()*1000,"yyyy-MM-dd");
				layout_cancelorder_time.setText(time+"");
				layout_cancelorder_address.setText(queryOrderDetailsRes.getAddr());
				layout_cancelorder_name.setText(queryOrderDetailsRes.getContact());
				if(queryOrderDetailsRes.getIsPay()==0){
					layout_cancelorder_sum.setText(Html.fromHtml("<small>¥</small>" + FormatTools.String2Money(queryOrderDetailsRes.getSumFee()+"")+"<small> ( 已支付 ) </small>"));
				}else{
					layout_cancelorder_sum.setText(Html.fromHtml("<small>¥</small>" + FormatTools.String2Money(queryOrderDetailsRes.getSumFee()+"")));
				}
				// 判断该用户是新/老用户
				if (queryOrderDetailsRes.getSex()==1) {
					layout_cancelorder_sex.setText("小姐");
				} else if (queryOrderDetailsRes.getSex()==2){
					layout_cancelorder_sex.setText("先生");
				}else{
					layout_cancelorder_sex.setText("");
				}
				
				// 重置列表
				goodsList.clear();
				//添加商品
				if(queryOrderDetailsRes.getGoodsList()!=null&&queryOrderDetailsRes.getGoodsList().size()>0){
					goodsList.addAll(queryOrderDetailsRes.getGoodsList());
				}
				//外送费
				if(queryOrderDetailsRes.getDeliverFee()>0){
					DeliverFee deliverFee=new DeliverFee();
					deliverFee.setPrice(queryOrderDetailsRes.getDeliverFee());
					goodsList.add(deliverFee);
				}
				//餐盒费
				if(queryOrderDetailsRes.getBoxFee()>0){
					BoxFee boxFee=new BoxFee();
					boxFee.setType(queryOrderDetailsRes.getBoxType());
					boxFee.setNum(queryOrderDetailsRes.getBoxNum());
					boxFee.setPrice(queryOrderDetailsRes.getBoxFee());
					goodsList.add(boxFee);
				}
				//添加赠品
				if(queryOrderDetailsRes.getGiftList()!=null&&queryOrderDetailsRes.getGiftList().size()>0){
					goodsList.addAll(queryOrderDetailsRes.getGiftList());
				}
				//添加优惠券
				if(queryOrderDetailsRes.getCouponList()!=null&&queryOrderDetailsRes.getCouponList().size()>0){
					goodsList.addAll(queryOrderDetailsRes.getCouponList());
				}
				//添加备注
				if(!TypeJudgeTools.isNull(queryOrderDetailsRes.getRemark())){
					Remark remark=new Remark();
					remark.setRemark(queryOrderDetailsRes.getRemark());
					goodsList.add(remark);
				}

				cancelOrderAdapter = new CancelOrderAdapter(getActivity(),goodsList);
				layout_cancelorder_lv.setAdapter(cancelOrderAdapter);

			}
		});
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_cancelorder_agree:
			agreeCancel();
			break;
		case R.id.layout_cancelorder_disagree:
			disagreeCancel();
			break;
		}
	}

	/**
	 * 同意取消订单
	 */
	public void agreeCancel() {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					HandleCancelReq handleCancelReq=new HandleCancelReq();
					handleCancelReq.setoId(homeActivity.homeController.cancelOrderList.get(0));
					handleCancelReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					handleCancelReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					handleCancelReq.setHandle(1);
					Result<HandleCancelRes> result=orderModel.handleCancel(handleCancelReq);
					Log.i("order", ""+homeActivity.homeController.cancelOrderList.get(0));
					// 移除取消订单列表的第一个数据并将新的cancelOrderList存储到aCache中
					homeActivity.homeController.cancelOrderList.remove(0);
					if(result!=null&&result.getCode()==1){
						HandleCancelRes handleCancelRes=result.getData();
						//将该订单移到无效订单里
						omModel.moveOrder2Invalid(handleCancelRes.getoId(), handleCancelRes.getStatus());
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "操作成功！");
								homeActivity.getOrderFm().orderController.refreshUnsendData();
								homeActivity.getOrderFm().orderController.refreshSendData();
								homeActivity.getOrderFm().orderController.refreshInvalidData();
							}
						});
					}else if(result!=null&&result.getCode()==-3){
						homeActivity.homeController.exitLogin();
					}else{
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "操作失败！");
								homeActivity.getOrderFm().orderController.refreshUnsendData();
								homeActivity.getOrderFm().orderController.refreshSendData();
								homeActivity.getOrderFm().orderController.refreshInvalidData();
							}
						});
					}
					
					// 判断订单列表cancelOrderList.size()是否为小于0，如果小于0返回订单页面，如果大于0继续接单
					int hasData = homeActivity.homeController.cancelOrderList.size();
					if (hasData <= 0) {
						homeActivity.openFM(new FmInfo(OrderFragment.class, "",false));
						LightManager.turnOnRedLight(false);
						SoundManager.getInstance(getActivity()).stopSound();
						// 隐藏蒙版，使actionbar上的点击事件可用
						homeActivity.menuView.menuViewController.hideMask();
					} else {
						initData();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 拒绝取消订单
	 */
	public void disagreeCancel() {

		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					HandleCancelReq handleCancelReq=new HandleCancelReq();
					handleCancelReq.setoId(homeActivity.homeController.cancelOrderList.get(0));
					handleCancelReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					handleCancelReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					handleCancelReq.setHandle(2);
					Result<HandleCancelRes> result=orderModel.handleCancel(handleCancelReq);
					// 移除取消订单列表的第一个数据并将新的cancelOrderList存储到aCache中
					homeActivity.homeController.cancelOrderList.remove(0);
					if(result!=null&&result.getCode()==1){
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "操作成功！");
								homeActivity.getOrderFm().refreshUnSendOrder();
								homeActivity.getOrderFm().refreshInvalidOrder();
							}
						});
					}else if(result!=null&&result.getCode()==-3){
						homeActivity.homeController.exitLogin();
					}else{
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "操作失败！");
								homeActivity.getOrderFm().refreshUnSendOrder();
								homeActivity.getOrderFm().refreshInvalidOrder();
							}
						});
					}
					
					// 判断订单列表cancelOrderList.size()是否为小于0，如果小于0返回订单页面，如果大于0继续接单
					int hasData = homeActivity.homeController.cancelOrderList.size();
					if (hasData <= 0) {
						Class clazzFM=homeActivity.getCurrentFragment().getClass();
						homeActivity.openFM(new FmInfo(clazzFM,null,false));
						// 关灯关声音
						SoundManager.getInstance(getActivity()).stopSound();
						LightManager.turnOnRedLight(false);
						// 隐藏蒙版，使actionbar上的点击事件可用
						homeActivity.menuView.menuViewController.hideMask();
					} else {
						initData();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});

	}
}
